using System.Net.Sockets;
using System.Net;

namespace Fusion.Net.TCP
{
    public class TCPClient : TCPNet
    {
        TCPClientSocket tcpClientSocket;
        public TCPClient(string ip, int port)
        {
            if (NetUtility.OSSupportsIPv6())
            {
                CreateSocket(ip, port, AddressFamily.InterNetworkV6);
            }
            else if (NetUtility.OSSupportsIPv4())
            {
                CreateSocket(ip, port, AddressFamily.InterNetwork);
            }
        }

        public void SetHeartBeats(float interval)
        {
            tcpClientSocket.SetHeartBeats(interval);
        }

        public void SetHeartBeatsResponseChecker(float interval)
        {
            tcpClientSocket.SetHeartBeatsResponseChecker(interval);
        }

        public TCPClient(string ip, int port, AddressFamily addressFamily)
        {
            CreateSocket(ip, port, addressFamily);
        }

        private void CreateSocket(string ip, int port, AddressFamily addressFamily)
        {
            socket = new TCPClientSocket(this, addressFamily);
            if (socket.Socket.AddressFamily == AddressFamily.InterNetworkV6)
            {
                socket.Bind(IPAddress.Parse(ip).MapToIPv6(), port);
            }
            else if (socket.Socket.AddressFamily == AddressFamily.InterNetwork)
            {
                socket.Bind(IPAddress.Parse(ip), port);
            }
            tcpClientSocket = (TCPClientSocket)socket;
        }

        public void Send(byte[] data, int length = -1)
        {
            socket?.Send(data, length > 0 ? length : data.Length);
        }
    }

}

